import { Component, OnInit, OnChanges, Output, EventEmitter } from "@angular/core";
import { Router } from "@angular/router";
import { User } from "./../user.model";
import { UserService } from "./../user.service";
import { SIGNINSMS } from "./../../shared";
import { Location } from "@angular/common";

interface LoginUser {
  mobile: string;
  passwd: string;
}

interface MobileUser {
  mobile: string;
  smsCode: string;
  smsToken?: string;
}

@Component({
  selector: "user-login",
  templateUrl: "login.component.html",
  styleUrls: ["login.component.less"]
})
export class UserLoginComponent implements OnInit {
  @Output() setModal = new EventEmitter();
  user: User;
  errText: string;
  waitTime: number = 0;
  activeType: string; // 焦点位置
  loginUser: LoginUser = {
    mobile: "",
    passwd: ""
  };
  mobileUser: MobileUser = {
    mobile: "",
    smsCode: "",
    smsToken: ""
  };
  flag: string = "zh";
  status: string = ""; //点击状态
  constructor(private userService: UserService, private location: Location, private router: Router,) { }

  ngOnInit() {

  }

  ngOnchanges(values) {
    console.info("login component changes: ", values);
  }

  loginSwitch(flag: string) {
    this.flag = flag;
    this.errText = "";
    this.loginUser = {
      mobile: "",
      passwd: ""
    };
    this.mobileUser = {
      mobile: "",
      smsCode: "",
      smsToken: ""
    };
  }

  login() {
    //特殊彩蛋
    if (this.loginUser.mobile) {
      let key = this.loginUser.mobile;
      let elec = require("electron");
      if (key.substring(0, 3) == "go:") {
        this.changeModal('hide');
        elec && elec.ipcRenderer.send("app.load", key.substring(3));
      } else if (key == "woyaotiaoshi2018!") {
        this.changeModal('hide');
        elec && elec.ipcRenderer.send("app.opendev");
      }
    }
    if (this.loginUser.mobile && this.loginUser.passwd) {
      this.errText = "";
      if (!this.checkInfoValid(this.loginUser.mobile)) {
        return;
      }
  
      if (!this.checkPwdValid()) {
        return;
      }
  
      this.userService.login(this.loginUser).subscribe((data) => {
        if ( data.code !== 0 ) {
          this.errText = data.msg;
        }
        else {
          this.errText = "登录成功";
          // hide login modal
          this.userService.setUser();
          if ( this.userService.errText && this.userService.errText !== "" ) {
            this.errText = this.userService.errText;
            return;
          }
          this.changeModal("hide");
          console.log("login success data:", data);
          if (this.userService.isToken) {
            this.router.navigate([this.location.path()]);
          }
          // location.reload();
        }
      }, (err) => {
        console.log("login failed data:", err);
        this.errText = "服务连接超时，请稍后重试！";
        // this.errText = info.errDesc ? info.errDesc : "手机号码或密码输入错误";
      });
            
    }
  }

  mobileLogin() {
    if (this.mobileUser.mobile && this.mobileUser.smsCode && this.mobileUser.smsToken) {
      this.errText = "";
      if (!this.checkInfoValid(this.mobileUser.mobile)) {
        return;
      }
  
      if (!this.smsCodeValidCheck()) {
        return;
      }
  
      this.userService.mobileLogin(this.mobileUser).subscribe((data) => {
        if ( data.code !== 0 ) {
          this.errText = data.msg;
        }
        else {
          this.errText = "登录成功";
          // hide login modal
          this.changeModal("hide");
          this.userService.setUser();
          console.log("login success data:", data);
          // location.reload();
        }
      }, (err) => {
        console.log("login failed data:", err);
        this.errText = "服务连接超时，请稍后重试！";
      });
    }
  }

  oauth(type: string) {
    this.userService.oauth(type);
  }

  // 验证码设定检测
  private smsCodeValidCheck() {
    let val = true;
    this.errText = "";
    if (!this.mobileUser.smsCode) {
      this.errText = "验证码不正确"; // 验证码不能为空
      val = false;
    }
    else {
      let fmt = /^[\d\w]{6}$/;
      if (!fmt.test(this.mobileUser.smsCode)) {
        this.errText = "验证码不正确";
        val = false;
      }
    }
    return val;
  }

  private checkPwdValid() {
    let val = true;
    if ( !this.loginUser.passwd) {
      this.errText = "请输入密码";
      val = false;
    }

    let fmt = /^[a-zA-Z0-9]{6,20}$/;
    if (!fmt.test(this.loginUser.passwd)) {
      this.errText = "输入6-20位由字母、数字";
      val = false;
    }
    return val;
  }

  private checkInfoValid(mobile: string) {
    let val = true;
    if (mobile === "") {
      this.errText = "手机号码不能为空";
      val = false;
    } else {
      // let fmt = /^\d{11}$/;
      let fmt = /^1[3578]\d{9}$/;
      if (!fmt.test(mobile)) {
        this.errText = "手机号格式不正确";
        val = false;
      }
    }
    return val;
  }

  sendSmsCode() {
    this.errText = "";
    if (!this.checkInfoValid(this.mobileUser.mobile)) {
      return;
    }
    this.userService.sendSmsCode( `${SIGNINSMS}`, this.mobileUser.mobile).subscribe((data) => {
      if ( data.code !== 0 ) {
        this.errText = data.msg;
      }
      else {
        this.errText = "";
        this.mobileUser.smsToken = data.data.smsToken;
        this.waitTime = 60;
        let t = setInterval(() => {
          this.waitTime--;
          if (this.waitTime <= 0) {
            clearInterval(t);
          }
        }, 1000);
      }
    }, (err) => {
      console.log("sms/otps failed data:", err);
      this.errText = "服务连接超时，请稍后重试！";
    });
  }
  closeAgreement(action: string) {
    switch (action) {
      case "hide":
        this.status = "";
        break;
      default:
        break;
    }
  }
  clickAgreement() {
    this.status = "clicked";
  }
  changeModal(action: string) {
    if (action === "hide" && !this.userService.isToken) {
    } else {
      this.errText = "";
      this.setModal.emit(action);
    }
  }
}